var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: false}));
//自己加的模块
var partials = require('express-partials');
var util=require('util');
var settings = require('./settings');
var cookieParser = require('cookie-parser');
var session = require("express-session");
var MongoStore=require("connect-mongo")(session);
var flash=require("connect-flash");
var routes = require('./routes/index');
var users = require('./routes/users');
var multer= require('multer');


//使用cookie中间件
app.use(cookieParser());
//会话中间件，把session存放在mongoDB 中，而不是存到内存中
app.use(session({
  secret: settings.cookieSecret,
  cookie: {maxAge: 1000*60*60*24*30 },//毫秒，设置什么时候清除，不写默认为null，这样当浏览器关闭时就会自动清空
  resave: false,
  saveUninitialized: true,
  //把会话信息存储到数据库中，这样就不会因为浏览器关闭而自动清空，可以做那种两周内记住密码功能
  store:new MongoStore({
    db: settings.db,
    url: 'mongodb://localhost/Travel'
  })
}));
//使用multer实现文件上传功能
app.use(multer({
	dest:'./public/upload_imgs',//设置上传的文件所在的目录 
	rename:function(fieldname,filename){//修改上传的后的文件名  这里设置为保存原来的文件名
		return filename;
	}
}));
//使用中间件来返回成功和失败的信息
app.use(function(req,res,next){
  //声明变量
  var err=req.session.error;
  var msg=req.session.success;
  //删除会话中原有属性
  delete req.session.error;
  delete req.session.success;
  //将错误和正确信息存放到动态视图助手变量中
  res.locals.message='';
  //if(err) res.locals.message='<div class="alert alert-error">'+err+'</div>';
  if(err) res.locals.message='<div class="alert alert-warning alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'+err+'</div>';
  //if(msg) res.locals.message='<div class="alert alert-success">'+msg+'</div>';
  if(msg) res.locals.message='<div class="alert alert-success alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'+msg+'</div>';
  next();
});

//使用中间件把user设置成动态视图助手
//app.use(function(req,res,next){
//res.locals.user = req.session.user;
//next();
//});

// 设置模板文件的存储位置和使用的模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(flash());
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(partials());
app.use(logger('dev'));


app.use(cookieParser());
//将静态文件目录设置为public文件夹   
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}


app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
